//
//  FSearchViewController.m
//  YiQiTingShu
//
//  Created by dllo on 15/11/7.
//  Copyright © 2015年 直到世界的尽头. All rights reserved.
//

#import "FSearchViewController.h"
#import "PublicHeader.h"
#import "FSearchModel.h"
#import <UIImageView+WebCache.h>
#import "WHNTableViewCell.h"
#import "AlbumFViewController.h"
#import "ResultViewController.h"

@interface FSearchViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain)UISearchBar *searchBar;
@property(nonatomic, retain)NSMutableArray *searchArray;
@property(nonatomic, assign)NSInteger flag;
@property(nonatomic, retain)UITableView *tableView;
@end
static NSString *identifier = @"cell";
@implementation FSearchViewController

-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableFooterView = [[UIView alloc] init];
        [_tableView   NightWithType:UIViewColorTypeNormal];
    }
    
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"搜索结果";
    [self.view NightWithType:UIViewColorTypeNormal];
    
    _searchArray = [NSMutableArray array];
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, FitConstant_YorHeight(50))];
    _searchBar.placeholder = @"请输入要查找的内容";
    _searchBar.delegate = self;
    self.navigationItem.titleView = _searchBar;
    
    [self.view addSubview:self.tableView];
//    [self searchBarShouldBeginEditing:_searchBar];
//    [self searchBarTextDidBeginEditing:_searchBar];
//    [self searchBar:_searchBar textDidChange:@""];
    [self.searchBar becomeFirstResponder];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _searchArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row < 2) {
        static NSString *identifierCell = @"imageCell";
        WHNTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierCell];
        if (!cell) {
            cell = [[WHNTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierCell];
            cell.kind = WHNTableViewCellKindThree;
        }
        FSearchModel *search = _searchArray[indexPath.row];
        cell.TitleLabel.text = search.keyword;
        [cell.MainImageView sd_setImageWithURL:[NSURL URLWithString:search.imgPath]];
        cell.NameLabel.text = search.category;
        cell.NameLabel.frame = FitRectMake(260, 40, 80, 40);
        [cell.CountLabel NightWithType:UIViewColorTypeClear];
        return cell;
    }
    else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        [cell NightWithType:UIViewColorTypeNormal];
        [cell.textLabel NightWithType:UIViewColorTypeNormal];
        FSearchModel *search = _searchArray[indexPath.row];
        cell.textLabel.text = search.keyword;
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < 2) {
        return FitConstant_YorHeight(120);
    }
    return FitConstant_YorHeight(50);
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < 2) {
        AlbumFViewController *vc = [[AlbumFViewController alloc] init];
        FSearchModel *search = _searchArray[indexPath.row];
        vc.albumId = [NSString stringWithFormat:@"%@", search.albumId];
        vc.alumbTitel = search.keyword;
        [self.navigationController pushViewController:vc animated:NO];
    }
    else{
        ResultViewController *vc = [[ResultViewController alloc] init];
        vc.searchString = [_searchArray[indexPath.row] keyword];
        [self.navigationController pushViewController:vc animated:NO];
    }
}

#pragma mark - searchBar的代理方法
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    self.flag = 1;
    if (![searchText isEqualToString:@" "]) {
        NSMutableString *string = [NSMutableString stringWithString:searchText];
        while ([string hasPrefix:@" "]) {
            NSRange range;
            range.location = 0;
            range.length = 1;
            [string deleteCharactersInRange:range];
        }
        if (string != nil) {
            [self tableViewInitData:string];
        }
    }
    
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = YES;
    for(id cc in [searchBar subviews])
    {
        if([cc isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:@"取消"  forState:UIControlStateNormal];
        }
    }
    
    [self tableViewInitData:@""];
    
    //出现返回按钮
//    [self.navigationController.view addSubview:_button];
    [_tableView reloadData];
    return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    searchBar.text = @"";
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    self.flag = 0;
    searchBar.showsCancelButton = NO;
}

//点击搜索框上的 取消按钮时 调用
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    self.searchBar.text = @"";
    [_searchBar resignFirstResponder];
    self.searchBar.showsCancelButton = NO;
//    [_button removeFromSuperview];
//    _isSearch = NO;
    [_tableView reloadData];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self resignFirstResponder];
}

-(void)tableViewInitData:(NSString *)string
{
    //移除上次搜索内容
    [_searchArray removeAllObjects];
    if ([string isEqualToString:@""]) {
//        _isSearch = YES;
        return;
    }
    
    [AFTools getDataByURLString:[NSString stringWithFormat:@"http://search.ximalaya.com/suggest?device=iPhone&kw=%@", string] WithDataBlock:^(id data) {
        [_searchArray removeAllObjects];
        for (NSDictionary *each in [data objectForKey:@"albumResultList"]) {
            FSearchModel *search = [[FSearchModel alloc] init];
            [search setValuesForKeysWithDictionary:each];
            [_searchArray addObject:search];
        }
        for (NSDictionary *each in [data objectForKey:@"queryResultList"]) {
            FSearchModel *search = [[FSearchModel alloc] init];
            [search setValuesForKeysWithDictionary:each];
            [_searchArray addObject:search];
        }
        [_tableView reloadData];
    }];
}

-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    if ([self.searchBar isFirstResponder]) {
        [self.searchBar resignFirstResponder];
        //        [self.view endEditing:YES];
    }
}



@end
